package com.lagou.controller;

import com.lagou.client.RpcConsumerManager;
import com.lagou.req.RequestInfo;
import com.lagou.service.UserService;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import java.util.*;

/**
 * @author xsl
 * @date 2021/4/5 23:32
 * @Description: UserController
 */
@RestController
@RequestMapping("/user")
public class UserController {

    @RequestMapping("sayHello")
    @ResponseBody
    public String sayHello(String name){
        Map<String, RequestInfo> requestInfoMap = RpcConsumerManager.getRequestInfoMap();
        UserService userService = null;
        if(requestInfoMap.keySet().size() > 0){
            List<RequestInfo> requestInfos  = new ArrayList<>(requestInfoMap.values());
            if(requestInfos.size() == 1){
                userService = (UserService)requestInfos.get(0).getRpcConsumer().createProxy(UserService.class);
            }else {
                //实现负载均衡逻辑
                RequestInfo[] arr = requestInfos.toArray(new RequestInfo[requestInfos.size()]);
                //根据请求耗时升序排列
                Arrays.sort(arr, new Comparator<RequestInfo>() {
                    @Override
                    public int compare(RequestInfo o1, RequestInfo o2) {
                        return o1.getElapsedTime() - o2.getElapsedTime();
                    }
                });
                RequestInfo first = arr[0];
                RequestInfo last = arr[arr.length - 1];
                //如果时间一致，随机选取一个服务端进行调用
                if(first.getElapsedTime() == last.getElapsedTime()){
                    int index = new Random().nextInt(arr.length);
                    userService = (UserService)arr[index].getRpcConsumer().createProxy(UserService.class);
                }else{
                    //每次都选择最后一次响应时间短的服务端进行服务调用
                    userService = (UserService)first.getRpcConsumer().createProxy(UserService.class);
                }
            }
        }
        if(userService != null){
            return userService.sayHello(name);
        }
        return "服务器异常请稍后重试！";
    }
}
